using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using MapsterMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Cache;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using FytSoa.DynamicApi.Attributes;
using Masuit.Tools.Security;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
    
namespace FytSoa.Application.Sys;

/// <summary>
/// 管理员表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v1")]
public class SysAdminService : SugarRepository<SysAdmin>,ISysAdminService 
{
    private readonly IMapper _mapper;
    public SysAdminService(IMapper mapper)
    {
        _mapper = mapper;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ApiResult<PageResult<SysAdminDto>>> GetPagesAsync(PageParam param)
    {
        var where = Expressionable.Create<SysAdmin>()
            .AndIF(!string.IsNullOrEmpty(param.Key),
                m => m.FullName.Contains(param.Key) || m.Mobile.Contains(param.Key) || m.Email.Contains(param.Key) ||
                     m.LoginAccount.Contains(param.Key))
            .AndIF(!string.IsNullOrEmpty(param.Status), m => m.Status == (param.Status == "1"))
            .AndIF(param.Id!=1 && param.Id!=0,m=> m.RoleGroupParent.ToString()!.Contains(param.Id.ToString()));
        var (list,totalItems,totalPage) = await base.GetPageResultAsync(where.ToExpression(), param.Page, param.Limit, m => m.Id);
        var groupDb = base.ChangeRepository<SugarRepository<SysRole>>();
        var groupList = await groupDb.GetListAsync();
        var resList = _mapper.Map<List<SysAdminDto>>(list);
        foreach (var item in resList)
        {
            var group = groupList.Where(m => item.RoleGroup.Contains(m.Id.ToString()));
            item.RoleGroupName = string.Join(",", group.Select(m => m.Name).ToArray());;
        }
        var result = new PageResult<SysAdminDto>()
        {
            Items = resList,
            TotalItems = totalItems,
            TotalPages = totalPage
        };
        return JResult<PageResult<SysAdminDto>>.Success(result);
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ApiResult<SysAdminDto>> GetAsync(long id)
    {
        var model = _mapper.Map<SysAdminDto>(await base.GetByIdAsync(id));
        model.LoginPassWord = model.LoginPassWord.AESDecrypt();
        return JResult<SysAdminDto>.Success(model);
    }
    
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="loginParam"></param>
    /// <returns></returns>
    [NonDynamicMethod]
    public async Task<ApiResult<SysAdminDto>> LoginAsync(LoginParam loginParam)
    {
        var code = MemoryService.Default.GetCache<string>(KeyUtils.CAPTCHACODE+loginParam.CodeKey);
        if (!string.Equals(code, loginParam.Code, StringComparison.CurrentCultureIgnoreCase)) return JResult<SysAdminDto>.Error("验证码输入错误！~");

        var model = await base.GetSingleAsync(m=> !m.IsDel && m.LoginAccount==loginParam.Account);
        if (model == null) return JResult<SysAdminDto>.Error("账号输入错误！~");

        if (model.LoginPassWord != loginParam.Password.AESEncrypt()) return JResult<SysAdminDto>.Error("密码输入错误！~");

        if (!model.Status) return JResult<SysAdminDto>.Error("账号被冻结，请联系管理员！~");

        model.LoginTime = DateTime.Now;
        model.LoginCount += 1;
        model.UpLoginTime = model.LoginTime;
        await base.UpdateAsync(model);

        var resDto = _mapper.Map<SysAdminDto>(model);
        return JResult<SysAdminDto>.Success(resDto);
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> AddAsync(SysAdminDto model)
    {
        model.Id = Unique.Id();
        model.LoginPassWord = model.LoginPassWord.AESEncrypt();
        model.RoleGroup = new List<string>();
        foreach (var item in model.RoleGroupParent)
        {
            model.RoleGroup.Add(item.Last());
        }
        if (model.OrganizeIdList.Count>0)
        {
            model.OrganizeId = long.Parse(model.OrganizeIdList.Last());
        }
        return JResult<bool>.Success(await base.InsertAsync(_mapper.Map<SysAdmin>(model)));
    }
    
    /// <summary>
    /// 密码重置
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task<ApiResult<bool>> PassResetAsync(List<long> id)
    {
        var newPwd = "123456a!".AESEncrypt();
        return JResult<bool>.Success(await base.UpdateAsync(m => new SysAdmin()
        {
            LoginPassWord =newPwd
        }, m => id.Contains(m.Id)));
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> ModifyAsync(SysAdminDto model)
    {
        model.LoginPassWord = model.LoginPassWord.AESEncrypt();
        model.RoleGroup = new List<string>();
        foreach (var item in model.RoleGroupParent)
        {
            model.RoleGroup.Add(item.Last());
        }
        if (model.OrganizeIdList.Count>0)
        {
            model.OrganizeId = long.Parse(model.OrganizeIdList.Last());
        }
        return JResult<bool>.Success(await base.UpdateAsync(_mapper.Map<SysAdmin>(model)));
    }

    /// <summary>
    /// 删除,支持多个
    /// </summary>
    /// <param name="ids">逗号分隔</param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<ApiResult<bool>> DeleteAsync(string ids)
    {
        return JResult<bool>.Success(await base.DeleteAsync(m=>ids.StrToListLong().Contains(m.Id)));
    }
}
